package com.rayframework.boot.config;

import com.ray.tool.RayStringTools;
import com.ray.tool.file.RayFileTools;
import com.rayframework.boot.helper.RayMyBatisPlusHelper;
import com.rayframework.context.RayApplicationContext;
import com.rayframework.context.annontion.AnnotationConfigApplicationContext;
import com.rayframework.context.utils.ApplicationConfigUtils;
import com.rayframework.context.utils.RayConsoleUtils;
import com.rayframework.context.utils.RayContextUtils;

import java.io.*;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * 框架配置 - application.properties
 * IOC生成
 *
 * @author LiaoYuXing-Ray
 * @version 1.0
 * @createDate 2023/9/8 9:04
 **/
public class ApplicationConfig {
    /**
     * 初始化标记 2023/9/12 15:32
     */
    private static boolean isInitialized = false;

    /**
     * IOC 容器 2023/9/13 14:55
     */
    public static AnnotationConfigApplicationContext context;// 暂时设计为不允许用户创建

    public static AnnotationConfigApplicationContext getContext() {
        return context;
    }

    /**
     * 加载框架配置
     *
     * @author LiaoYuXing-Ray 2023/9/8 14:59
     **/
    public synchronized static void init() {
        if (!isInitialized) {
            /*
             * 框架第1个加载 - 框架启动环境准备 2023/9/14 9:46
             */
            RayApplicationContext.init();

            /*
             * 加载导航图 2023/9/13 13:19
             */
            if (RayContextUtils.checkProperty("Ray.init.banner.print")) {
                loadBanner();
            }

            /*
             * 加载IOC容器 2023/9/13 13:20
             */
            if (RayContextUtils.checkPropertyUse("Ray.ioc.init.use")) {
                String annotationPackagePath = RayApplicationContext.getApplicationPropertyValue("Ray.ioc.scan.component.basePackages");
                if (annotationPackagePath != null && !"".equals(annotationPackagePath)) {
                    context = new AnnotationConfigApplicationContext(annotationPackagePath);
                } else {
                    RayConsoleUtils.error("IOC容器路径加载异常：" + annotationPackagePath);
                }
            }

            /*
             * 加载核心帮助类 2023/9/13 13:21
             */
//            ConfigHelper.init();

            /*
             * 初始化 MyBatisPlus工具 2023/9/13 13:21
             */
            if (RayContextUtils.checkPropertyUse("Ray.init.MyBatisPlus.use")) {
                System.out.println("123");
                RayMyBatisPlusHelper.init();
            }

            // 标记已经初始化
            isInitialized = true;
        }

    }


    /**
     * 加载banner.txt
     * 如果用户内配置了banner，直接打印用户自定义的banner，否则打印框架默认
     *
     * @author LiaoYuXing-Ray 2023/9/7 14:11
     **/
    private static void loadBanner() {
        // application中配置打印banner才打印
        try {
            // 获取banner路径
            String bannerFileName = RayApplicationContext.getApplicationPropertyValue("Ray.init.banner.file.name");
            String filePath = RayFileTools.pathCombine(1, ApplicationConfigUtils.getAppRoot(),
                    "src", "main", "resources", bannerFileName);

            // 创建File对象
            File file = new File(filePath);
            // 判断文件是否存在
            if (file.exists()) {
                // 打印banner
                System.out.println(RayFileTools.readFileByFilePath(filePath));
            } else {
                String jarPath = RayContextUtils.getRayJar();
                if (RayStringTools.isNotBlank(jarPath)) {
                    try (JarFile jarFile = new JarFile(jarPath)) {
                        // 枚举jar包中的所有条目
                        Enumeration<JarEntry> entries = jarFile.entries();
                        while (entries.hasMoreElements()) {
                            JarEntry entry = entries.nextElement();
                            String name = entry.getName();
                            if (name.endsWith("banner.txt")) { // 只读取以"banner.txt"结尾的文件，此处限制名字，防止异常
                                try (InputStream inputStream = jarFile.getInputStream(entry);
                                     BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
                                    String line;
                                    while ((line = reader.readLine()) != null) {
                                        System.out.println(line); // 输出banner
                                    }
                                } catch (IOException e) {
                                    System.out.println("Error reading file: " + name);
                                    e.printStackTrace();
                                }
                            }
                        }
                    } catch (IOException e) {
                        System.out.println("Error opening jar file: " + jarPath);
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
